using System;
using Microsoft.SPOT;
using NeonMika.Webserver.EventArgs;
using System.Collections;
using System.Threading;
using System.IO;
using SecretLabs.NETMF.Hardware;
using SecretLabs.NETMF.Hardware.NetduinoPlus;
using CodingSmackdown.Services;
using FastloadMedia.NETMF.Http;


namespace CodingSmackdown.TemperatureMonitor
{
    public class GetHistoryMethod
    {
        public static bool GetHistory(RequestReceivedEventArgs e, JsonArray h)
        {
            try
            {
                Settings settings = new Settings();
                settings.loadSettings();

                string[] values = null;
                string line;
                float temperatureValue;
                JsonArray resultValues = new JsonArray();
                using (StreamReader file = new StreamReader(@"\SD\" + settings.HistoryFilename))
                {
                    // Read and display lines from the file until the end of 
                    // the file is reached.
                    while ((line = file.ReadLine()) != null)
                    {
                        values = line.Split(',');
                        if ((values != null) && (values.Length >= 3))
                        {
                            if (TryParseFloat(values[4], out temperatureValue))
                            {
                                resultValues.Add(temperatureValue);
                            }
                        }
                    }
                }

                h.Add(resultValues);
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.Message);
            }

            return true;
        }

        public static bool TryParseFloat(string s, out float result)
        {
            bool success = true;
            int decimalDiv = 0;
            result = 0;
            try
            {
                for (int i = 0; i < s.Length; i++)
                {
                    if (s[i] == '.' && decimalDiv == 0)
                        decimalDiv = 1;
                    else if (s[i] < '0' || s[i] > '9')
                        success = false;
                    else
                    {
                        result = result * 10;
                        decimalDiv = decimalDiv * 10;
                        result += (int)(s[i] - '0');
                    }
                }
                result = (float)result / decimalDiv;
            }
            catch
            {
                success = false;
            }
            return success;
        }
    }
}
